#!/usr/bin/python
# -*- coding: utf-8 -*-

from plan_dispatch_simulation.plan_dispatch_simulation import *
import sys

device_sim= ('XL002','002')

def get_sent(device_sim):
    group_id, unit_id = device_sim[:]
    objs = []
    sql = "SELECT a.obj_id FROM object_list_current a, object_list_all b WHERE a.obj_id=b.obj_id AND a.obs_stag='sent' AND b.group_id='" + \
        group_id + "' AND (b.unit_id='" + unit_id + "' OR (b.unit_id LIKE '%|%'  AND b.unit_id LIKE '%" + unit_id + \
        "%' )) AND a.mode='observation' ORDER BY a.id LIMIT 10"
    res = sql_act(sql)
    if res:
        for i in res:
            objs.append(i[0])
    return objs

def type_input():
    while True:
        try:
            cmd = input(
'''\nPlease confirm the simulation:
    1 The observation is COMPLETE
    2 The observation is BROKEN
>>>:''')
        except KeyboardInterrupt:
            exit()
        except:
            print('\nPlease try again for input error.')
            continue
        else:
            if not cmd or int(cmd) not in [1,2]:
                print('\nPlease try again for input error.')
            else:
                return cmd

def check_sim(obj):
    print('\nObservation status of {}: observing'.format(obj))
    cmd = int(type_input())
    if cmd == 1:
        print('\nObservation status of {}: complete'.format(obj))
        client_pd.Send({"obj_id": obj, "obs_stag": 'complete'}, ['update', 'object_list_current', 'obs_stag'])
    else:
        print('\nObservation status of {}: broken'.format(obj))
        client_pd.Send({"obj_id": obj, "obs_stag": 'break'}, ['update', 'object_list_current', 'obs_stag'])
        print('\nThe objects are being planned...')
    msg = get_msg()
    if msg:
        if cmd == 2:
            print('\nThe objects have been planned')
            send_sim()
        return True

def send_sim():
    new_objs = get_objs_new(device_sim)
    if new_objs:
        obj = new_objs[0]
        print('\nGet the new object: {}'.format(obj))
        time.sleep(1)
        print('\nObservation status of {}: sending'.format(obj))
        time.sleep(3)
        print('\nObservation status of {}: sent'.format(obj))
        client_pd.Send({"obj_id": obj, "obs_stag": 'sent'}, ['update', 'object_list_current', 'obs_stag'])
        if check_sim(obj):
            return True
    else:
         print('\nThere are no new objects in the daatbase. End of simulation.')

def end_sim():
    print('\nThe objects have been planne. The system has got a new object, it will open a new round of observatio. End of simulation.')

def sim(num):
    print('\n')
    for i in range(num+1):
        sys.stdout.write('\rThe simulation will begin in {} seconds <using device: ("XL002","002")> ...'.format(num-i))
        sys.stdout.flush()
        if (num-i) > 0:
            time.sleep(1)
    print('\n')
    print('\nThe objects are being planned...')
    client_og.Send()
    msg = get_msg()
    if msg:
        print('\nThe objects have been planned')
        sent_objs = get_sent(device_sim)
        if sent_objs:
            obj = sent_objs[0]
            print('\nGet the incomplete object: {}'.format(obj))
            if check_sim(obj):
                if send_sim():
                    end_sim()
        else:
            if send_sim():
                end_sim()

if __name__ == '__main__':
    ### Presupposition：the objects in the example has benn imported；using device ('XL002','002')
    sim(3)
